import React from 'react'
import {
  FlatButton,
  Dialog,
  TextField,
} from 'material-ui'

import {
  inject,
  observer,
} from 'mobx-react'

@inject(stores => {
  return {
    appStore: stores.appStore,
    user: stores.appStore.user,
  }
})
@observer
class Login extends React.Component {
  static muiName = "FlatButton"
  constructor() {
    super()
    this.state = {
      open: false,
      login: {
        username: "",
        password: ""
      }
    }
  }

  openLogin = () => {
    this.setState({
      open: true
    })
  }

  closeLogin = () => {
    this.setState({
      open: false,
      login: {
        username: "",
        password: ""
      }
    })
  }

  inputUsername = (event) => {
    this.setState({
      login: {
        username: event.target.value,
        password: this.state.login.password
      }
    })
  }

  inputPassword = (event) => {
    this.setState({
      login: {
        username: this.state.login.username,
        password: event.target.value
      }
    })
  }

  loginFn(userInfo) {
    return this.props.appStore.login(userInfo)
  }

  login = () => {
    const userInfo = this.state.login
    this.loginFn(userInfo)
  }

  render() {
    let username = this.state.login.username
    let password = this.state.login.password

    const actions = [
      <FlatButton
        label="登录"
        primary={true}
        onClick={this.login}
      />,
      <FlatButton
        label="取消"
        onClick={this.closeLogin}
      />,
    ]

    const { appStore, ...style } = this.props

    return [
      <FlatButton
        {...style}
        label="登录"
        key="login"
        onClick={this.openLogin}
      />,
      <FlatButton
        {...style}
        label="注册"
        key="register"
      />,
      <Dialog
        title="登录"
        actions={actions}
        open={this.state.open}
        onRequestClose={this.closeLogin}
        key="openDialog"
      >
        <TextField
          hintText="输入用户名"
          fullWidth={true}
          id="username"
          type="text"
          value={username}
          onChange={this.inputUsername}
        />
        <br/>
        <TextField
          hintText="输入密码"
          fullWidth={true}
          id="password"
          type="password"
          value={password}
          onChange={this.inputPassword}
        />
      </Dialog>,
    ]
  }
}

export default Login
